//
//  TSRechargeConfirmInfoTableViewCell.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/6.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

extension NSNotification.Name {
    public static let TSRechargeCommitNotification = Notification.Name("TSRechargeCommitNotification")
}

protocol TSRechargeConfirmInfoTableViewCellDelegate : NSObjectProtocol {
    func fitToCommit(usdt:String, name:String)
}

extension TSRechargeConfirmInfoTableViewCell : UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
        let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
        let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
        return numberOfMatches != 0
    }
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        
        let usdt = NSString.init(string: usdtField.text ?? "0")
        cashField.text = String.init(format: "%.2f", usdt.doubleValue * rate)
    }
}

class TSRechargeConfirmInfoTableViewCell: UITableViewCell {

    weak var delegate : TSRechargeConfirmInfoTableViewCellDelegate? = nil
    
    var usdtField : UITextField!
    var cashField : UITextField!
    var nameField : UITextField!
    var rate : Double = 0
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        configViews()
    
        NotificationCenter.default.addObserver(self, selector: #selector(self.rechargeCommitNotification), name: .TSRechargeCommitNotification, object: nil)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        NotificationCenter.default.addObserver(self, selector: #selector(self.rechargeCommitNotification), name: .TSRechargeCommitNotification, object: nil)
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupRate(rate:Double) {
        self.rate = rate
    }
    
    @objc private func rechargeCommitNotification() {
        
        if checkCommitAviliable() {
            
            if self.delegate != nil {
                
                IQKeyboardManager.shared().resignFirstResponder()
                self.delegate?.fitToCommit(usdt: usdtField.text!, name: nameField.text!)
            }
        }
    }
    
    private func checkCommitAviliable() -> Bool {
        
        let usdt = Int64(usdtField.text?.removeAllSapce ?? "")
        if usdt == 0 {
            CBToast.showToastAction(message: "请输入存款金额")
            return false
        }
        
        let name = nameField.text?.removeAllSapce ?? ""
        if name.count == 0 {
            CBToast.showToastAction(message: "请输入存款人姓名")
            return false
        }
        
        return true
    }
    
    func configViews() {
        
        let dateLabel = createLabel(text: "存款时间")
        self.contentView.addSubview(dateLabel)
        dateLabel.snp.makeConstraints { (make) in
            make.left.equalTo(26)
            make.top.equalTo(18)
            make.width.equalTo(85)
        }
                
        let dateInfoLabel = createLabel(text: Date.currentTime(formatter: "YYYY-MM-dd HH:mm"))
        self.contentView.addSubview(dateInfoLabel)
        dateInfoLabel.snp.makeConstraints { (make) in
            make.left.equalTo(dateLabel.snp.right)
            make.top.equalTo(dateLabel)
            make.right.equalToSuperview().inset(-26)
        }
        
        let line1 = drawLine()
        self.contentView.addSubview(line1)
        line1.snp.makeConstraints { (make) in
            make.left.equalTo(12)
            make.top.equalTo(dateInfoLabel.snp.bottom).offset(19)
            make.size.equalTo(CGSize(width: SCREEN_WIDTH - 2*12, height: 1))
        }
        
        usdtField = createInputField(placeholder: "请输入存款金额")
        usdtField.keyboardType = .decimalPad
        usdtField.delegate = self
        self.contentView.addSubview(usdtField)
        usdtField.snp.makeConstraints { (make) in
            make.left.equalTo(dateInfoLabel)
            make.right.equalToSuperview().offset(-26)
            make.top.equalTo(line1.snp.bottom)
            make.height.equalTo(50)
        }
        
        let usdtLabel = createLabel(text: "USDT")
        self.contentView.addSubview(usdtLabel)
        usdtLabel.snp.makeConstraints { (make) in
            make.left.equalTo(dateLabel)
            make.centerY.equalTo(usdtField)
            make.width.equalTo(dateLabel)
        }
        
        let line2 = drawLine()
        self.contentView.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.left.equalTo(line1)
            make.top.equalTo(usdtField.snp.bottom)
            make.size.equalTo(line1)
        }
        
        cashField = createInputField(placeholder: "请输入存款金额")
        cashField.text = "0.00"
        cashField.isEnabled = false
        self.contentView.addSubview(cashField)
        cashField.snp.makeConstraints { (make) in
            make.left.equalTo(dateInfoLabel)
            make.right.equalTo(usdtField)
            make.top.equalTo(line2.snp.bottom)
            make.height.equalTo(usdtField)
        }
        
        let cashLabel = createLabel(text: "RMB")
        self.contentView.addSubview(cashLabel)
        cashLabel.snp.makeConstraints { (make) in
            make.left.equalTo(dateLabel)
            make.centerY.equalTo(cashField)
            make.width.equalTo(dateLabel)
        }
        
        let line3 = drawLine()
        self.contentView.addSubview(line3)
        line3.snp.makeConstraints { (make) in
            make.left.equalTo(line1)
            make.top.equalTo(cashField.snp.bottom)
            make.size.equalTo(line1)
        }
        
        nameField = createInputField(placeholder: "请输入存款人姓名")
        self.contentView.addSubview(nameField)
        nameField.snp.makeConstraints { (make) in
            make.left.equalTo(dateInfoLabel)
            make.right.equalTo(usdtField)
            make.top.equalTo(line3.snp.bottom)
            make.height.equalTo(usdtField)
        }
        
        let nameLabel = createLabel(text: "存款人姓名")
        self.contentView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(dateLabel)
            make.centerY.equalTo(nameField)
            make.width.equalTo(dateLabel)
        }
        
        let line4 = drawLine()
        self.contentView.addSubview(line4)
        line4.snp.makeConstraints { (make) in
            make.left.equalTo(line1)
            make.top.equalTo(nameField.snp.bottom)
            make.size.equalTo(line1)
            
            make.bottom.equalTo(-10)
        }
        
    }
    
    func createLabel(text:String) -> UILabel {
        
        let label = UILabel.init()
        label.text = text
        label.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        return label
    }
    
    func createInputField(placeholder:String) -> UITextField {
        
        let attributeStr = NSMutableAttributedString.init(string: placeholder)
        attributeStr.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.hexadecimalColor(hexadecimal: "#989898"), NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: .medium)], range: NSMakeRange(0, placeholder.count))
        
        let textField = UITextField.init()
        textField.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        textField.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        textField.attributedPlaceholder = (attributeStr.copy() as! NSAttributedString)
        textField.borderStyle = .none
        textField.clearButtonMode = .whileEditing
        return textField
    }
    
    func drawLine() -> UIView {
        let line = UIView.init()
        line.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        return line
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
